import React, { useState, useEffect, useRef } from 'react';
import './styles.css';

const AddBarrage: React.FC = () => {
    const [inputValue, setInputValue] = useState('');
    const [messages, setMessages] = useState<string[]>([]);
    const danmakuContainerRef = useRef<HTMLDivElement>(null);

    const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        setInputValue(e.target.value);
    };

    const handleSendClick = () => {
        if (inputValue.trim()!== '') {
            setMessages([...messages, inputValue]);
            setInputValue('');
        }
    };

    useEffect(() => {
        const container = danmakuContainerRef.current;
        if (container) {
            const messagesElements = container.querySelectorAll('.danmaku');
            messagesElements.forEach((message) => {
                const messageWidth = message.offsetWidth;
                const containerWidth = container.offsetWidth;
                let leftPosition = containerWidth;
                const speed = Math.random() * 3 + 1; // 随机速度

                const intervalId = setInterval(() => {
                    leftPosition -= speed;
                    message.style.left = `${leftPosition}px`;
                    if (leftPosition < -messageWidth) {
                        clearInterval(intervalId);
                        message.remove();
                    }
                }, 20);
            });
        }
    }, [messages]);

    return (
        <div className="app-container">
            <div className="danmaku-container" ref={danmakuContainerRef}>
                {messages.map((message, index) => (
                    <div key={index} className="danmaku">
                        {message}
                    </div>
                ))}
            </div>
            <div className='dan'>
              <input
              className='con'
                type="text"
                placeholder="请输入弹幕内容"
                value={inputValue}
                onChange={handleInputChange}
            />
            <button className='out' onClick={handleSendClick}>发送</button>
            </div>
          
            
        </div>
    );
};

export default AddBarrage;
    